package com.hwtx.form.util.translate;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class TransApi {
    private static final String TRANS_API_HOST = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    private final String appid;
    private final String securityKey;
    private static final String APP_ID = "20240718002102755";
    private static final String SECURITY_KEY = "jpgtWhZW6Du8BWV4OsBf";

    public TransApi() {
        this(APP_ID, SECURITY_KEY);
    }

    public TransApi(String appid, String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }

    public String getEnTransResult(String query) {
        String ret = getTransResult(query, "auto", "en");
        try {
            JSONArray transResult = new JSONObject(ret).getJSONArray("trans_result");
            JSONObject firstResult = transResult.getJSONObject(0);
            ret = firstResult.getStr("dst");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return ret;
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

}
